package com.xdhl.fu.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.xdhl.fu.common.core.domain.R;
import com.xdhl.fu.common.core.utils.StringUtils;
import com.xdhl.fu.common.core.web.controller.BaseController;
import com.xdhl.fu.common.core.web.domain.AjaxResult;
import com.xdhl.fu.common.core.web.page.TableDataInfo;
import com.xdhl.fu.common.log.annotation.Log;
import com.xdhl.fu.common.log.enums.BusinessType;
import com.xdhl.fu.common.security.annotation.RequiresPermissions;
import com.xdhl.fu.flight.info.api.mongodb.domain.MGReservation;
import com.xdhl.fu.order.domain.OrderInfo;
import com.xdhl.fu.order.domain.RefundBody;
import com.xdhl.fu.order.domain.vo.OrderInfoVO;
import com.xdhl.fu.order.repository.MGReservationRepository;
import com.xdhl.fu.order.service.IOrderInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单退款控制层
 *
 * @author 朱力维
 * @time 2022/5/29 17:02
 */
@RestController
@RequestMapping("/refund")
public class OrderRefundController extends BaseController {
    @Resource
    private IOrderInfoService orderInfoService;

    @Resource
    private MGReservationRepository mgReservationRepository;

    /**
     * 查询退订列表
     */
    @RequiresPermissions("order:refund:list")
    @GetMapping("/list")
    public TableDataInfo list(OrderInfoVO orderInfoVO) {
        startPage();

        // 如果会员号不为空，则远程调用接口获取会员ID，并注入到条件值
        String memberDataId = "";
        if (null == memberDataId) {
            memberDataId = orderInfoVO.getMNumber();
        }
        LambdaQueryWrapper<OrderInfo> lqw = new LambdaQueryWrapper<>();
        // 只查询订单状态为退订中的订单
        lqw.eq(true, OrderInfo::getOStatus, "C");
        lqw.eq(StringUtils.isNotBlank(memberDataId), OrderInfo::getMemberDataId, memberDataId);
        String fNumber = orderInfoVO.getFlightDataId();
        lqw.eq(StringUtils.isNotBlank(fNumber), OrderInfo::getFlightDataId, fNumber);
        List<OrderInfo> list = orderInfoService.list(lqw);
        long total = new PageInfo<>(list).getTotal();
        List<OrderInfoVO> infoVOS = new ArrayList<>();
        list.forEach(item -> {
            OrderInfoVO vo = new OrderInfoVO();
            BeanUtils.copyProperties(item, vo);
            vo.setMNumber("");
            infoVOS.add(vo);
        });
        return getDataTable(infoVOS, total);
    }

    /**
     * 同意退款申请
     */
    @RequiresPermissions("order:refund:agree")
    @Log(title = "同意退款", businessType = BusinessType.UPDATE)
    @PutMapping("/agree/{dataIds}")
    public AjaxResult agree(@PathVariable String[] dataIds) {
        for (int i = 0; i < dataIds.length; i++) {
            OrderInfo orderInfo = orderInfoService.getById(dataIds[i]);
            orderInfo.setOStatus("D");
            orderInfo.setChargebackStatus("B");
            orderInfo.setChargebackTime(null);
            orderInfoService.updateById(orderInfo);
        }
        return toAjax(true);
    }

    /**
     * 拒绝退款申请
     */
    @RequiresPermissions("order:refund:refuse")
    @Log(title = "拒绝退款", businessType = BusinessType.UPDATE)
    @PutMapping("/refuse/{dataIds}")
    public AjaxResult refuse(@PathVariable String[] dataIds) {
        for (int i = 0; i < dataIds.length; i++) {
            OrderInfo orderInfo = orderInfoService.getById(dataIds[i]);
            orderInfo.setOStatus("B");
            orderInfo.setChargebackStatus("C");
            orderInfo.setChargebackTime(null);
            orderInfoService.updateById(orderInfo);
        }
        return toAjax(true);
    }

    /**
     * 会员申请退票
     */
    @PutMapping
    public R<?> refund(@RequestBody RefundBody refundBody) {
        OrderInfo orderInfo = orderInfoService.getById(refundBody.getDataId());
        orderInfo.setOStatus("D");
        orderInfo.setChargebackStatus("B");
        orderInfo.setChargebackTime(LocalDateTime.now());
        MGReservation reservation = mgReservationRepository.findById(orderInfo.getSerialNumber()).get();
        reservation.setOrder(JSONObject.parseObject(JSONObject.toJSONString(orderInfo)));
        mgReservationRepository.save(reservation);
        orderInfoService.updateById(orderInfo);
        return R.ok(null, "该订单为预订订单，退票成功");
    }
}
